package com.netty.socket.service;

import com.netty.socket.gatewayClient.ChannelPool;
import com.netty.socket.gatewayClient.GatewayClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by Administrator on 2018/9/9/009.
 */
public class SocketServiceHandler extends SimpleChannelInboundHandler {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "==>连接成功==>" + ctx.channel().isActive());
        ctx.fireChannelActive();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                new GatewayClient().satrt();
//            }
//        }).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "==>" + msg);
        //ctx.writeAndFlush("服务端回应:收到");
//        Channel channel = ChannelPool.getChannel();
//        System.out.println(channel.isActive() + "===" + channel.isWritable());
//        Object obj = msg;
//        channel.writeAndFlush(obj);
        ctx.fireChannelRead(msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent)evt;

            String eventType = null;

            switch (event.state()) {
                //服务端的读空闲状态，超过设置的时间服务端没有收到任何数据触发
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                //服务端写空闲状态，超过设置的时间服务端没有向客户端写任何数据触发
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                //服务端读写空闲，超过设置的时间服务端没有读也没有写任何数据触发
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + " 超时事件:" + eventType);
            ctx.channel().close();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    }
}
